﻿-- GPLP ADDON METER BY HELTRAISER --

E_DM = LibStub("AceAddon-3.0"):NewAddon("E_DM", "AceConsole-3.0", "AceEvent-3.0") 
E_DM.version = tostring(GetAddOnMetadata("GPLP_DM", "Version"))
E_DM.name = "GPLP Damage Meter"
E_DM.bars={}
E_DM.LeftText={}
E_DM.RightText={}
E_DM.Index={}
local L = LibStub("AceLocale-3.0"):GetLocale("E_DM", true)
local media = LibStub("LibSharedMedia-3.0")
local Pets={}
local dbd
local TYPE_PET = (COMBATLOG_OBJECT_TYPE_PET or 0x00001000) + (COMBATLOG_OBJECT_TYPE_GUARDIAN or 0x00002000)
local TYPE_GAMER = (COMBATLOG_OBJECT_AFFILIATION_MINE or 0x00000001) + (COMBATLOG_OBJECT_AFFILIATION_PARTY or 0x00000002) + (COMBATLOG_OBJECT_AFFILIATION_RAID or 0x00000004)
local bitband = bit.band
local stringformat = string.format
local trem = tremove
local sorty = table.sort
local defaults = {
	global = {
		colorbg = {
			["r"] = 0,
			["g"] = 0,
			["b"] = 0,
			["a"] = 1,		 
		},
		colorborder = {
			["r"] = 1,
			["g"] = 1,
			["b"] = 1,
			["a"] = 1,		 
		},	
		color = {
			["r"] = 0.5,
			["g"] = 0.5,
			["b"] = 0.7,
			["a"] = 1,		 
		},	
		texcolor = {
			["r"] = 1,
			["g"] = 1,
			["b"] = 1,
			["a"] = 1,		 
		},
		MiniMap={},
		output = "",
		height = 16,
		width = 230,
		fontsize = 12,
		font = 1,	
		tex = 1,
		scale = 1,
		interval = 3,
		classcolor = false,
		channel = "<opcion deshabilitada>",
		vis = true,
		ovrdmg = true,
		scrollbar = true,
		strata="HIGH",
		lock = false,
	},
}

local function CreateBar(i)
	E_DM.bars[i] = CreateFrame("StatusBar",nil,E_DM.container)
	E_DM.bars[i]:SetStatusBarTexture(media:Fetch("statusbar",E_DM.db.global.tex))
	if dbd.scrollbar==true then
		E_DM.bars[i]:SetWidth(E_DM.header:GetWidth()-27)
	else
		E_DM.bars[i]:SetWidth(E_DM.header:GetWidth()-15)
	end
	E_DM.bars[i]:SetHeight(dbd.height)
	E_DM.bars[i]:SetStatusBarColor(dbd.color.r, dbd.color.g, dbd.color.b, dbd.color.a)
	E_DM.bars[i]:SetMinMaxValues(0, 100)
	E_DM.bars[i]:SetValue(100)
	E_DM.bars[i]:SetPoint("TOPLEFT",8,(i*-dbd.height)+dbd.height-7)
	E_DM.bars[i]:EnableMouse(true)
	E_DM.bars[i]:SetScript('OnLeave', function() GameTooltip:Hide() end)
	E_DM.bars[i]:Hide()
	E_DM.LeftText[i] = E_DM.bars[i]:CreateFontString(nil, 'OVERLAY')	
	E_DM.LeftText[i]:SetTextColor(dbd.texcolor.r,dbd.texcolor.g,dbd.texcolor.b,dbd.texcolor.a)
	E_DM.LeftText[i]:SetPoint("LEFT", E_DM.bars[i], 24+dbd.fontsize, 0)
	E_DM.LeftText[i]:SetFont(media:Fetch("font",dbd.font),dbd.fontsize)
	E_DM.RightText[i] = E_DM.bars[i]:CreateFontString(nil, 'OVERLAY')		
	E_DM.RightText[i]:SetTextColor(dbd.texcolor.r,dbd.texcolor.g,dbd.texcolor.b,dbd.texcolor.a)		
	E_DM.RightText[i]:SetPoint("RIGHT", E_DM.bars[i], -4, 0)	
	E_DM.RightText[i]:SetFont(media:Fetch("font",dbd.font),dbd.fontsize)
	E_DM.Index[i] = E_DM.bars[i]:CreateFontString(nil, 'OVERLAY')
	E_DM.Index[i]:SetTextColor(dbd.texcolor.r,dbd.texcolor.g,dbd.texcolor.b,dbd.texcolor.a)		
	E_DM.Index[i]:SetPoint("LEFT", E_DM.bars[i], 4, 0)
	E_DM.Index[i]:SetFont(media:Fetch("font",dbd.font),dbd.fontsize)	
	E_DM.Index[i]:SetText("#"..i)				
end

--Eliminado una funcion inutil.

local function GetSortedData()
	local count = 0	
	local temp={}
	local max=0
	for _,v in pairs(E_DMdmg) do
		max=max+v[2]
	end	
	for k,v in pairs(E_DMdmg) do
		count=count+1
		temp[count] = {["name"]=v[1],["dmg"]=v[2],["perc"]=(v[2]/max)*100, ["col"]=v[3],} 
	end	
	sorty(temp, function(a,b) return a.dmg > b.dmg end)
	return temp		
end


local function AddData(srcGUID, srcName, amount, overkill, timestamp)
	if tonumber(amount)==nil then return end 
	if not dbd.ovrdmg then
		amount = amount - overkill
	end
	srcName=srcName or "Unknown"	
	if not E_DMdmg[srcGUID] then 
		local Class
		 _, Class = UnitClass(srcName)
		E_DMdmg[srcGUID]={[1]=srcName,[2]=0, [3]=RAID_CLASS_COLORS[Class] } 
	end
	E_DMdmg[srcGUID][2]=E_DMdmg[srcGUID][2]+amount

end

function E_DM:UpdateFrame()
	local count = 0
	local temp=GetSortedData()
	local dmgk
	for _,v in ipairs(temp) do		
		dmgk=v.dmg
		count=count+1
		if not E_DM.bars[count] then CreateBar(count) end
		E_DM.bars[count]:Show()
		E_DM.LeftText[count]:SetText(v.name)
		if dmgk >= 100000 then dmgk=stringformat("%.1fk",dmgk/1000) end
		E_DM.RightText[count]:SetText(dmgk..stringformat(" (%.2f%%)",v.perc))
		E_DM.bars[count]:SetValue((v.dmg/temp[1].dmg)*100)
		if dbd.classcolor and v.col then
			E_DM.bars[count]:SetStatusBarColor(v.col.r, v.col.g, v.col.b, 1)
		else
			E_DM.bars[count]:SetStatusBarColor(dbd.color.r, dbd.color.g, dbd.color.b, dbd.color.a)
		end		
	end
	if count==0 then count=2 end
	E_DM.container:SetHeight((count*dbd.height)+13)
	E_DM.MainFrame:UpdateScrollChildRect()	
end		

function E_DM:OnCmd(arg1)
	local arg1,arg2=string.split(" ", arg1)
	if arg1=="lanzar" then
		E_DM:UpdateFrame()
		E_DM.MainFrame:Show()
	else
		if E_DM.MainFrame:IsVisible() then E_DM.MainFrame:Show() else E_DM.MainFrame:Show() end		
	end		
end	
									
function E_DM:OnEnable()
	E_DM:RegisterChatCommand('edm', 'OnCmd') 
	local t=GetTime() --Eliminado una parte 
	E_DM.MainFrame:SetScript("OnShow", function() 
		dbd.vis=true
		E_DM.MainFrame:SetScript('OnUpdate', function() 
			if GetTime()-t<dbd.interval then return end 
			t=GetTime()
			E_DM:UpdateFrame() 
		end) 
	end)
	--dbd.trackdps = true
	E_DM.MainFrame:Hide()
	E_DM.MainFrame:SetScript("OnHide", function() dbd.vis=false E_DM:UpdateFrame() E_DM.MainFrame:SetScript('OnUpdate', nil) end)
	E_DM.MainFrame:SetScale(dbd.scale)
	E_DM.header = CreateFrame("Frame", nil, E_DM.MainFrame)
	E_DM.header:SetWidth(E_DM.MainFrame:GetWidth())
	E_DM.header:SetHeight(26)	
	E_DM.header:EnableMouse(true)
	E_DM.header:SetHitRectInsets(1, 30, 1, 1)
	E_DM.header:RegisterForDrag("LeftButton")
	E_DM.header:SetPoint("TOPLEFT", E_DM.MainFrame, "TOPLEFT", 0, 21)
	E_DM.header:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background", 
		edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
		tile = true, tileSize = 16, edgeSize = 16, 
		insets = { left = 4, right = 4, top = 4, bottom = 4 }})
	E_DM.header:SetBackdropBorderColor(dbd.colorborder.r, dbd.colorborder.g, dbd.colorborder.b, dbd.colorborder.a)
	E_DM.header:SetBackdropColor(dbd.colorbg.r, dbd.colorbg.g, dbd.colorbg.b, dbd.colorbg.a)		
	E_DM.header:SetScript("OnDragStart", function()
		if dbd.lock then return end		
		if(arg1 == "LeftButton") then			
			E_DM.MainFrame:StartMoving()
			E_DM.MainFrame:SetUserPlaced(true)	
		end
	end)		
	E_DM.header:SetScript("OnDragStop", function()
		E_DM.MainFrame:StopMovingOrSizing()
		E_DM.MainFrame:SetUserPlaced(true)	
	end)
	
	local closebutton = CreateFrame("Button", nil, E_DM.MainFrame, "UIPanelCloseButton")
	closebutton:SetPoint("TOPRIGHT", self.header, "TOPRIGHT", 3, 3)
	closebutton:SetScale(1)
	closebutton:SetScript('OnClick', function() E_DM.MainFrame:Hide() end)
	
	local Titel = E_DM.header:CreateFontString(nil, 'OVERLAY')		
	Titel:SetTextColor(0.95,0.95,0,1)		
	Titel:SetPoint("LEFT", E_DM.header, 10, 0)
	Titel:SetFont(GameFontNormal:GetFont(),12)
	Titel:SetText("GPLP Damage Meter")
	
	E_DM.footer = CreateFrame("Frame", nil, E_DM.MainFrame)
	E_DM.footer:SetWidth(E_DM.MainFrame:GetWidth())
	E_DM.footer:SetHeight(24)	
	E_DM.footer:SetPoint("TOP", E_DM.MainFrame, "BOTTOM",0,5)
	E_DM.footer:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background", 
		edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
		tile = true, tileSize = 16, edgeSize = 16, 
		insets = { left = 4, right = 4, top = 4, bottom = 4 }});
	E_DM.footer:SetBackdropBorderColor(dbd.colorborder.r, dbd.colorborder.g, dbd.colorborder.b, dbd.colorborder.a)
	E_DM.footer:SetBackdropColor(dbd.colorbg.r, dbd.colorbg.g, dbd.colorbg.b, dbd.colorbg.a)
	
	local reset = CreateFrame("Button", nil, E_DM.MainFrame)	
	reset:SetNormalTexture("Interface\\BUTTONS\\UI-GroupLoot-Pass-Up")
	reset:SetHighlightTexture("Interface\\BUTTONS\\UI-GroupLoot-Pass-Highlight", "ADD")	
	reset:SetWidth(16)
	reset:SetHeight(16)
	reset:SetPoint("LEFT", self.footer, "LEFT", 4, 0.5)
	reset:SetScript('OnClick', function()
			E_DMdmg={} 
			for o=1,#E_DM.bars do
				E_DM.bars[o]:Hide()
			end
			self:UpdateFrame()	 
	end)
	reset:SetScript('OnEnter', function() 	
		GameTooltip:ClearLines()
		GameTooltip:SetOwner(reset, "ANCHOR_BOTTOMLEFT")
		GameTooltip:AddLine("Resetear")
		GameTooltip:SetScale(0.8)
		GameTooltip:Show()
	end)
    
reset:SetScript('OnLeave', function() GameTooltip:Hide() GameTooltip:SetScale(1) end)    

-- Reprogramado toda la funcion

local report = CreateFrame("Button", nil, E_DM.MainFrame)
	report:SetScript('OnEnter', function() 	
		GameTooltip:ClearLines()
		GameTooltip:SetScale(0.8)
		GameTooltip:Hide()
	end)
	
	report:SetScript('OnLeave', function() GameTooltip:hide() GameTooltip:SetScale(1) end)	
	
	local sizer = CreateFrame("Button", nil, E_DM.footer)
	sizer:SetNormalTexture("Interface\\CURSOR\\Item")
	sizer:SetHighlightTexture("Interface\\CURSOR\\Item")	
	sizer:GetNormalTexture():SetTexCoord(1,0,1,0)
	sizer:GetHighlightTexture():SetTexCoord(1,0,1,0)
	sizer:SetHitRectInsets(10, 0, 10, 0) 
    sizer:GetNormalTexture():SetVertexColor(1, 1, 1, 0.3)    
	sizer:SetWidth(32)
	sizer:SetHeight(32) 
	sizer:SetPoint("RIGHT", self.footer, "RIGHT", -4, 8.5)
	sizer:SetScript('OnMouseDown', function()
		sizer:SetScript('OnUpdate', function() 
			E_DM.header:SetWidth(E_DM.MainFrame:GetWidth()) 
			E_DM.footer:SetWidth(E_DM.MainFrame:GetWidth())
			E_DM.container:SetWidth(E_DM.MainFrame:GetWidth())
			for i=1,#E_DM.bars do
				E_DM.bars[i]:SetWidth(E_DM.MainFrame:GetWidth()-27)
			end 
		end) 
		E_DM.MainFrame:StartSizing() 
	end)
	sizer:SetScript('OnMouseUp', function() E_DM.MainFrame:StopMovingOrSizing() sizer:SetScript('OnUpdate', nil) dbd.width = E_DM.MainFrame:GetWidth() E_DM.MainFrame:SetUserPlaced(true) end)
	self:UpdateFrame()		
	if dbd.vis == true then E_DM.MainFrame:Show() else E_DM.MainFrame:Hide() end 	
	-- no tenemos boton de minimap -> el siguiente if sobra
	--if IsAddOnLoaded("GPLP_DM_Minimap") then E_DM:CreateMiniMap() end -- en esta parte se carga el modulo del minimapa.
end		

function E_DM:DoReport(arg1,arg2)
	local chat = {[1]="GPLP Damage Meter",}
	local temp=GetSortedData()	
	local dmgk		
	for k,v in pairs(temp) do
		dmgk=v.dmg
		if dmgk >= 100000 then dmgk=stringformat("%.1fk",dmgk/1000) end
		chat[#chat+1]="#"..k.." "..v.name..": "..dmgk..stringformat(" (%.2f%%)",v.perc)
	end
	for k,v in ipairs(chat) do
		if k > 11 then return end
		if arg2 then
			SendChatMessage(v, "WHISPER", string.upper(GetDefaultLanguage()), UnitName("target") or "<No Target>")
		else
			SendChatMessage(v, dbd.output, nil, dbd.channel)
		end
	end
end

function E_DM:OnInitialize()
	E_DM.db = LibStub('AceDB-3.0'):New('E_DMDB')
	E_DM.db:RegisterDefaults(defaults)
	dbd = E_DM.db.global
	if not E_DMdmg then E_DMdmg={} end
	self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")	
	E_DM.MainFrame = CreateFrame("ScrollFrame", "E_DMMainFrame", UIParent, "UIPanelScrollFrameTemplate")
	E_DM.container = CreateFrame("Frame", "E_DMContainer", E_DM.MainFrame)
	E_DM.MainFrame:SetScrollChild(E_DM.container)	
	E_DM.MainFrame:SetVerticalScroll(dbd.height)
	E_DM.MainFrame:SetWidth(dbd.width)
	if not E_DM.MainFrame:IsUserPlaced() then E_DM.MainFrame:SetPoint("CENTER",0,20) end
	E_DM.container:SetAllPoints(E_DM.MainFrame)
	E_DM.container:SetWidth(dbd.width)
	E_DM.container:SetHeight(dbd.height-34)
	E_DM.MainFrame:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background", 
		edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
		tile = false, tileSize = 16, edgeSize = 16, 
		insets = { left = 4, right = 4, top = 4, bottom = 4 }})
	E_DM.MainFrame:SetBackdropBorderColor(dbd.colorborder.r, dbd.colorborder.g, dbd.colorborder.b, dbd.colorborder.a)
	E_DM.MainFrame:SetBackdropColor(dbd.colorbg.r, dbd.colorbg.g, dbd.colorbg.b, dbd.colorbg.a)					
	E_DM.MainFrame:SetHeight((25*dbd.height)+13)
	E_DM.MainFrame:SetResizable(true)
	E_DM.MainFrame:SetFrameStrata(dbd.strata)
	E_DM.MainFrame:SetClampedToScreen(true)
	E_DM.MainFrame:SetMovable(true)
	E_DM.MainFrame:SetMinResize(230, 29)	
	if dbd.scrollbar==true then E_DMMainFrameScrollBar:SetScale(0.7) else E_DMMainFrameScrollBar:SetScale(0.00000001) end
    E_DMMainFrameScrollBar:SetPoint("TOPLEFT", E_DM.MainFrame, "TOPRIGHT", -24,-25)
	E_DMMainFrameScrollBar:SetPoint("BOTTOMLEFT", E_DM.MainFrame, "BOTTOMRIGHT", -24,24)	
end

-- FindOwnerPetFromGUID funcion, meritos para el que la hizo.
local function FindOwnerPetFromGUID(petName,petGUID)
	local ownerName
	local ownerGUID
	for i = 1, GetNumRaidMembers(), 1 do 
		if petGUID == UnitGUID("raidpet"..i) then
			ownerName = UnitName("raid"..i)
			ownerGUID = UnitGUID("raid"..i)
			Pets[petGUID]={[1]=ownerGUID,[2]=ownerName or ""}
			return
		end
	end
	for i = 1, GetNumPartyMembers(), 1 do 
		if petGUID == UnitGUID("partypet"..i) then
			ownerName = UnitName("party"..i)
			ownerGUID = UnitGUID("party"..i)
			Pets[petGUID]={[1]=ownerGUID,[2]=ownerName or ""}
			return
		end
	end
	if petGUID==UnitGUID("pet") then
			ownerName = UnitName("player")
			ownerGUID = UnitGUID("player")
			Pets[petGUID]={[1]=ownerGUID,[2]=ownerName or ""}			
			return
	end
	Pets[petGUID]={[1]="XXXXXXXXXXXX",[2]="DESCONOCIDO/A"}	
	return
end

function E_DM:SpellDmg(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags,spellId, spellName, spellSchool, amount, overkill)
	AddData(srcGUID, srcName, amount, overkill or 0, timestamp)
end

function E_DM:HitDmg(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, amount, overkill)
	AddData(srcGUID, srcName, amount, overkill or 0, timestamp)
end

function E_DM:Summon(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID)
	Pets[dstGUID]={[1]=srcGUID,[2]=srcName or "Unknown"}
end

local events = {
	["SPELL_DAMAGE"] = E_DM.SpellDmg,
	["SPELL_PERIODIC_DAMAGE"] = E_DM.SpellDmg,
	["DAMAGE_SHIELD"] = E_DM.SpellDmg,
	["RANGE_DAMAGE"] = E_DM.SpellDmg,
	["DAMAGE_SPLIT"] = E_DM.SpellDmg,
	["SPELL_EXTRA_ATTACKS"] = E_DM.SpellDmg,
	["SPELL_SUMMON"] = E_DM.Summon,
	["SWING_DAMAGE"] = E_DM.HitDmg,
	["SWING_EXTRA_ATTACKS"] = E_DM.HitDmg,		
}

function E_DM:COMBAT_LOG_EVENT_UNFILTERED(call, timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags,spellId, spellName, spellSchool, amount, overkill, school, resisted, blocked, absorbed, critical, glancing, crushing)
	if bitband(srcFlags, TYPE_GAMER)==0 or not events[eventtype] then return end
	if bitband(srcFlags, TYPE_PET)==0 then
		events[eventtype](call, timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags,spellId, spellName, spellSchool, amount, overkill, school, resisted, blocked, absorbed, critical, glancing, crushing)
	else
		if not Pets[srcGUID] then 			
			FindOwnerPetFromGUID(srcName, srcGUID)
		end	
		events[eventtype](call, timestamp, eventtype, Pets[srcGUID][1], Pets[srcGUID][2], srcFlags, dstGUID, dstName, dstFlags,spellId, spellName, spellSchool, amount, overkill, school, resisted, blocked, absorbed, critical, glancing, crushing)
	end	
end